# -*- coding:UTF-8 -*-
'''
Copyright 2009 http://code.google.com/p/mygaepy/. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above
    copyright notice, this list of conditions and the following
    disclaimer in the documentation and/or other materials provided
    with the distribution.
  * Neither the name of http://code.google.com/p/mygaepy/ nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
import StringIO
import struct 
import urllib2
import logging
import random
import time

from google.appengine.api import memcache
from google.appengine.runtime import apiproxy_errors
from google.appengine.ext import db
from google.appengine.api import users

from models import *
from config import *


def getImageInfo(data):
#http://code.google.com/p/diabloimage/source/browse/trunk/DiabloImage/src/getimageinfo.py
    data = str(data)
    size = len(data)
    height = -1
    width = -1
    content_type = ''
    # handle GIFs
    if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'):
        # Check to see if content_type is correct
        content_type = 'image/gif'
        w, h = struct.unpack("<HH", data[6:10])
        width = int(w)
        height = int(h)
    # See PNG 2. Edition spec (http://www.w3.org/TR/PNG/)
    # Bytes 0-7 are below, 4-byte chunk length, then 'IHDR'
    # and finally the 4-byte width, height
    elif ((size >= 24) and data.startswith('\211PNG\r\n\032\n')
          and (data[12:16] == 'IHDR')):
        content_type = 'image/png'
        w, h = struct.unpack(">LL", data[16:24])
        width = int(w)
        height = int(h)
    # Maybe this is for an older PNG version.
    elif (size >= 16) and data.startswith('\211PNG\r\n\032\n'):
        # Check to see if we have the right content type
        content_type = 'image/png'
        w, h = struct.unpack(">LL", data[8:16])
        width = int(w)
        height = int(h)
    # handle JPEGs
    elif (size >= 2) and data.startswith('\377\330'):
        content_type = 'image/jpeg'
        jpeg = StringIO.StringIO(data)
        jpeg.read(2)
        b = jpeg.read(1)
        try:
            while (b and ord(b) != 0xDA):
                while (ord(b) != 0xFF): b = jpeg.read(1)
                while (ord(b) == 0xFF): b = jpeg.read(1)
                if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
                    jpeg.read(3)
                    h, w = struct.unpack(">HH", jpeg.read(4))
                    break
                else:
                    jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
                b = jpeg.read(1)
            width = int(w)
            height = int(h)
        except struct.error:
            pass
        except ValueError:
            pass
    return content_type, width, height

def getSysInfo():
    sysinfo=None
    try:
        sysinfo=memcache.get("SysInfo_")
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)
    if sysinfo is not None:
        return sysinfo
    sys=db.GqlQuery ("SELECT * FROM SysInfo")
    for s in sys:
        sysinfo=s
        try:
            r=memcache.set("SysInfo_",sysinfo)
            if not r:
                logging.error("Memcache set sysinfo failed.")
        except apiproxy_errors.OverQuotaError, message:
            logging.error(message)
    return sysinfo

def setSysInfo(sysinfo):
    sysinfo.put()
    try:
        r=memcache.set("SysInfo_",sysinfo)
        if not r:
            logging.error("Memcache set sysinfo failed.")
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)

def register_user(user, ip):
    """
    register the user and set a LoginLog    
    """
    userid = user.user_id()
    query = User.gql("WHERE user_id=:1", userid)
    u = query.fetch(1)
    if len(u) > 0:
        u = u[0]
    else:
        u = User()
        u.user_id = userid
        u.nickname = user.nickname()
        u.email = user.email()
        u.put()
    s = LoginLog()
    s.user_id = userid
    s.addr = ip
    s.put()
    
def getPicture(id,oid=0):
    picture=None
    found=False
    try:
        picture=memcache.get("picuture_%d"%id)
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)
    if picture is None:
        query = db.GqlQuery ("SELECT * FROM Picture WHERE picid=:1 AND ownerid=:2",id,oid)
        for img in query:
            picture=img
            if found:
                logging.error("more than one copy of picid:%d?"%id)
            found=True
        if picture is not None:
            try:
                r=memcache.add("picuture_%d"%id,picture)
                if not r:
                    logging.error("Memcache set failed.")
            except apiproxy_errors.OverQuotaError, message:
                logging.error(message)
    return picture

def getUserById(id):
    user=None
    try:
        user=memcache.get("userbyid_%d"%id)
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)
    if user is not None:
        return user
    query=db.GqlQuery ("SELECT * FROM User WHERE userid=:1",id)
    for u in query:
        user=u
        try:
            r=memcache.set("userbyid_%d"%id,user)
            if not r:
                logging.error("Memcache set user failed.")
        except apiproxy_errors.OverQuotaError, message:
            logging.error(message)
    return user

def saveUserId(id,user):
    user.put()
    try:
        r=memcache.set("userbyid_%d"%id,user)
        if not r:
            logging.error("Memcache set user failed.")
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)

def getAlbumById(albumid):
    album=None
    try:
        album=memcache.get("album_%d"%albumid)
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)
    if album is None:
        albums=db.GqlQuery ("SELECT * FROM Album WHERE albumid=:1",albumid)
        for a in albums:
            album=a
        if album:
            try:
                r=memcache.set("album_%d"%albumid,album)
                if not r:
                    logging.error("Memcache set album failed.")
            except apiproxy_errors.OverQuotaError, message:
                logging.error(message)
    return album

def getQuota(user):
    maxquota=100
    if users.is_current_user_admin():
        return 1
    else:
    	userid = user.user_id()
        from datetime import datetime
        quota=None
        quotas=db.GqlQuery ("SELECT * FROM Quota WHERE user_id=:1",userid)
        for q in quotas:
            quota = q
        if quota is None:
            quota = Quota()
            quota.user_id = userid
            quota.quota = maxquota
            quota.put()
        else:
            if quota.date.date() != datetime.now().date():
                quota.quota = maxquota
                quota.put()
        quota.quota-=1
        quota.put()
        return quota.quota
 
def getSession(key):
  session=None
  try:
    session=memcache.get("session_%s"%key)
  except apiproxy_errors.OverQuotaError, message:
    logging.error(message)
  if session is None:
    sessions=db.GqlQuery ("SELECT * FROM Session WHERE sessionkey=:1",key)
    for s in sessions:
      session=s
    if session:
       try:
         r=memcache.set("session_%s"%key,session)
         if not r:
           logging.error("Memcache set album failed.")
       except apiproxy_errors.OverQuotaError, message:
         logging.error(message)
  return session

def setSession(key,session):
  if session:
    try:
      r=memcache.set("session_%s"%key,session)
      if not r:
        logging.error("Memcache set album failed.")
    except apiproxy_errors.OverQuotaError, message:
      logging.error(message)
    session.put()
    